<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="queryParams.roomNumber"
          placeholder="请输入房间号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间名字" prop="roomName">
        <el-input
          v-model="queryParams.roomName"
          placeholder="请输入房间名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最大人数" prop="maxPeople">
        <el-input
          v-model="queryParams.maxPeople"
          placeholder="请输入最大人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:rooms:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 房间管理表格 -->
    <el-table
      v-loading="loading"
      :data="roomsList"
      @selection-change="handleSelectionChange"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="width: 100%;">
            <el-table
              :data="props.row.roomReservations"
              size="mini"
              style="width: 100%;"
              v-if="props.row.roomReservations && props.row.roomReservations.length"
              :header-cell-style="{ background: '#f5f7fa', color: '#333' }"
              border
            >
              <el-table-column label="预约人" align="center">
                <template slot-scope="scope">
                  {{ scope.row.userInfo?.userName || '未知' }}
                </template>
              </el-table-column>

              <el-table-column label="手机号" align="center">
                <template slot-scope="scope">
                  {{ scope.row.userInfo?.phonenumber || '-' }}
                </template>
              </el-table-column>

              <el-table-column prop="startTime" label="开始时间" align="center"/>
              <el-table-column prop="endTime" label="结束时间" align="center"/>
              <el-table-column prop="status" label="状态" align="center" width="100">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
                  <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
                  <el-tag v-else-if="scope.row.status === 2" type="danger">已取消</el-tag>
                  <el-tag v-else-if="scope.row.status === 4" type="danger">未通过</el-tag>
                  <el-tag v-else type="info">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="right" width="200">
                <template slot-scope="scope">
                  <div style="display: flex; justify-content: flex-end;">
                    <el-button
                      v-if="scope.row.status === 0"
                      type="primary"
                      size="mini"
                      style="width: 90px; margin-right: 8px;"
                      @click="changeReserveStatusInList(props.row, scope.row, 1)"
                    >审核通过</el-button>
                    <el-button
                      v-if="scope.row.status === 0"
                      type="danger"
                      size="mini"
                      style="width: 90px;"
                      @click="changeReserveStatusInList(props.row, scope.row, 4)"
                    >审核不通过</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div v-else style="color: #999; width: 100%; text-align: center;">暂无预约</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="房间ID" align="center" prop="id" />
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="房间名字" align="center" prop="roomName" />
      <el-table-column label="最大人数" align="center" prop="maxPeople" />
      <el-table-column label="房间说明" align="center" prop="roomDescription" />
      <el-table-column label="房间状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="预约列表"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="checkReserveList(scope.row.id)"
          >查看预约列表</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会议室管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="房间名字" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名字" />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxPeople">
          <el-input v-model="form.maxPeople" placeholder="请输入最大人数" />
        </el-form-item>
        <el-form-item label="房间说明" prop="roomDescription">
          <el-input
            v-model="form.roomDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预约日历弹窗 -->
    <el-dialog title="预约日历" :visible.sync="reserveVisibale" width="90%" append-to-body>
      <div style="max-height: 70vh; overflow: auto;">
        <full-calendar ref="fullCalendar" :options="calendarOptions" />
      </div>
    </el-dialog>


    <!-- 预约详情弹窗 -->
    <el-dialog title="预约详情" :visible.sync="showReservationDetail" width="600px" append-to-body class="reservation-detail-dialog">
      <el-form label-width="120px" disabled>
        <!-- 用户信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约用户">
              <el-input :value="selectedReservation?.userInfo?.userName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input :value="selectedReservation?.userInfo?.nickName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input :value="selectedReservation?.userInfo?.phonenumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input :value="selectedReservation?.userInfo?.email" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-input :value="selectedReservation?.userInfo?.sex" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-input :value="selectedReservation?.userInfo?.deptName" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属公司">
              <el-input :value="selectedReservation?.userInfo?.company" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select :value="selectedReservation?.userInfo?.roles" disabled placeholder="角色" style="width: 100%">
                <el-option
                  v-for="role in selectedReservation?.userInfo?.roles"
                  :key="role"
                  :label="role"
                  :value="role"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 预约信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约日期">
              <el-input :value="formatReservationDate(selectedReservation)" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约时长">
              <el-input :value="getReservationDuration(selectedReservation)" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-input :value="formatReservationStartTime(selectedReservation)" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-input :value="formatReservationEndTime(selectedReservation)" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约状态">
              <el-tag v-if="selectedReservation && selectedReservation.status === 0 && selectedReservation.endTime && new Date(selectedReservation.endTime) > new Date()" type="warning">待审核</el-tag>
              <el-tag v-else-if="selectedReservation && selectedReservation.status === 1 && selectedReservation.endTime && new Date(selectedReservation.endTime) > new Date()" type="success">审核通过</el-tag>
              <el-tag v-else-if="selectedReservation && selectedReservation.status === 2" type="danger">已取消</el-tag>
              <el-tag v-else-if="selectedReservation && selectedReservation.status === 4" type="danger">审核不通过</el-tag>
              <el-tag v-else-if="selectedReservation && selectedReservation.status === 0 && selectedReservation.endTime && new Date(selectedReservation.endTime) <= new Date()" type="info">已过期</el-tag>
              <el-tag v-else-if="selectedReservation && selectedReservation.status === 1 && selectedReservation.endTime && new Date(selectedReservation.endTime) <= new Date()" type="info">已完成</el-tag>
              <el-tag v-else type="info">未知状态</el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间状态">
              <el-tag :type="getTimeStatus(selectedReservation).type">{{ getTimeStatus(selectedReservation).text }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="预约备注">
          <el-input
            :value="selectedReservation && selectedReservation.remark"
            type="textarea"
            :rows="3"
            readonly
            placeholder="无备注信息"
          />
        </el-form-item>

        <el-form-item label="创建时间" v-if="selectedReservation && selectedReservation.createTime">
          <el-input :value="formatDateTime(selectedReservation.createTime)" readonly />
        </el-form-item>

        <el-form-item label="更新时间" v-if="selectedReservation && selectedReservation.updateTime">
          <el-input :value="formatDateTime(selectedReservation.updateTime)" readonly />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeReserveStatus(selectedReservation, 1)" v-if="selectedReservation && selectedReservation.status === 0 && selectedReservation.endTime && new Date(selectedReservation.endTime) > new Date()">审核通过</el-button>
        <el-button type="danger" @click="changeReserveStatus(selectedReservation, 4)" v-if="selectedReservation && selectedReservation.status === 0 && selectedReservation.endTime && new Date(selectedReservation.endTime) > new Date()">审核不通过</el-button>
        <el-button @click="showReservationDetail = false">关闭</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import {
  listRooms,
  getRooms,
  delRooms,
  addRooms,
  updateRooms
} from "@/api/system/rooms";
import { changeStatus } from "../../../api/system/rooms";

// 引入 FullCalendar 组件和插件
import FullCalendar from '@fullcalendar/vue';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
// 引入中文语言包
import zhLocale from '@fullcalendar/core/locales/zh-cn';
import dayjs from 'dayjs'
import { getUser } from '@/api/system/user'
export default {
  name: "Rooms",
  components: {
    FullCalendar // 注册组件
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      roomsList: [],
      ReserveList: [],
      title: "",
      open: false,
      reserveVisibale: false,
      showReservationDetail: false,
      selectedReservation: null,

      queryParams: {
        current: 1,
        pageSize: 10,
        roomNumber: null,
        roomName: null,
        maxPeople: null,
        roomDescription: null,
        status: null
      },
      form: {},
      rules: {
        roomNumber: [
          { required: true, message: "房间号不能为空", trigger: "blur" }
        ],
        roomName: [
          { required: true, message: "房间名字不能为空", trigger: "blur" }
        ],
        maxPeople: [
          { required: true, message: "最大人数不能为空", trigger: "blur" },
          // 只允许输入数字
          { pattern: /^(0|[1-9]\d*)$/, message: "最大人数必须为非负整数", trigger: "blur" },
          { type: "number", message: "最大人数必须为数字", trigger: "blur", transform: (value) => Number(value) }
        ]
      },
      searchId: null,

      // FullCalendar 配置
      calendarOptions: {
        plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
        initialView: 'timeGridWeek', // 只保留周视图
        initialDate: new Date(), // 强制从当天开始
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'timeGridWeek' // 只显示周视图按钮
        },
        locale: zhLocale,
        firstDay: 1, // 明确设置周一为一周的第一天（0是周日，1是周一）
        height: 'auto',
        contentHeight: 'auto',
        aspectRatio: 1.5, // 控制日历高度与宽度的比例
        fixedWeekCount: false, // 禁用固定6周模式
        showNonCurrentDates: false, // 隐藏非当前月的日期
        validRange: {
          start: new Date() // 只能查看今天及之后的日期
        },
        // 只保留周视图配置
        views: {
          timeGridWeek: {
            firstDay: 1
          }
        },
        // 视图日期变化回调
        datesSet: function(info) {
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          // 如果视图开始日期早于今天，强制跳转到今天
          if (new Date(info.start) < today) {
            this.getApi().gotoDate(today);
          }
        },
        // 事件点击处理
        eventClick: this.handleEventClick,
        // 事件显示内容
        eventContent: function(arg) {
          const startTime = dayjs(arg.event.start).format('HH:mm');
          const endTime = dayjs(arg.event.end).format('HH:mm');
          const startDate = dayjs(arg.event.start).format('MM-DD');
          const status = arg.event.extendedProps.status;
          const statusText = {
            0: '待审核',
            1: '已通过',
            2: '已取消',
            4: '未通过'
          }[status] || '未知';
          // 计算预约时长
          const duration = dayjs(arg.event.end).diff(dayjs(arg.event.start), 'hour', true);
          const durationText = duration >= 1 ? `${duration.toFixed(1)}小时` : `${Math.round(duration * 60)}分钟`;
          return {
            html: `
              <div class="fc-event-main" style="font-size: 10px; line-height: 1.1; padding: 2px;">
                <div style="margin-bottom: 1px; color: #fff; font-size: 9px;">
                  <span> ${startDate}</span>
                </div>
                <div style="margin-bottom: 1px; color: #fff; font-size: 9px;">
                  <span> ${startTime}-${endTime}</span>
                </div>
                <div style="margin-bottom: 1px; color: #fff; font-size: 9px;">
                  <span> ${durationText}</span>
                </div>
                <div style="margin-bottom: 1px; color: #fff; font-size: 9px;">
                  <span> ${statusText}</span>
                </div>
                <div style="color: #fff; font-size: 8px; word-break: break-all; max-height: 20px; overflow: hidden;">
                 备注： ${arg.event.extendedProps.remark ? ` ${arg.event.extendedProps.remark}` : ' 无备注'}
                </div>
              </div>
            `
          };
        },
        // 事件颜色根据状态
        eventDidMount: function(arg) {
          const status = arg.event.extendedProps.status;
          const colors = {
            0: '#f39c12', // 待审核
            1: '#28a745', // 已通过
            2: '#dc3545', // 已取消
            4: '#6c757d'  // 未通过
          };
          arg.el.style.backgroundColor = colors[status] || '#378006';
        }
      },
      userCache: {}, // 全局用户缓存
      roomLoading: {}, // 每个房间的 loading 状态
    };
  },

  created() {

    this.getList();
    this.$nextTick(() => {
      if (this.$refs.fullCalendar) {
        this.$refs.fullCalendar.getApi().updateSize();
        // 强制跳转到今天
        this.$refs.fullCalendar.getApi().gotoDate(new Date());
      }
    });
  },
  methods: {
    // 测试 getUser 接口的方法
    testGetUser(userId) {
      if (!userId) {
        this.$message.warning("请输入有效的用户ID");
        return;
      }

      this.loading = true;

      getUser(userId)
        .then(response => {
          this.loading = false;
          this.$message.success("请求成功，详情请查看控制台输出");

          // 可选：弹窗显示用户信息
          this.$alert(`<pre>${JSON.stringify(response.data, null, 2)}</pre>`, '用户信息', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定'
          });
        })
        .catch(error => {
          this.loading = false;
          console.error("请求失败:", error);
          this.$message.error("请求失败，请查看控制台日志");
        });
    },
    /** 查询会议室管理列表 */
    getList() {
      this.loading = true;
      listRooms(this.queryParams).then((response) => {
        this.roomsList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(err => {
        console.error('获取房间列表失败:', err);
        this.$message.error('获取房间列表失败，请重试');
        this.loading = false;
      });
    },
    checkReserveList(id) {
      this.searchId = id;
      this.loading = true;

      getRooms(id).then((response) => {
        const reservations = response.data.roomReservations || [];
        console.log('获取到的预约数据:', reservations);

        const events = reservations.map(reserve => ({
          id: reserve.id.toString(), // 确保事件有ID
          title: `预约人ID: ${reserve.userId}`,
          start: reserve.startTime,
          end: reserve.endTime,
          color: this.getStatusColor(reserve.status),
          extendedProps: reserve
        }));

        console.log('生成的事件数据:', events);

        // 正确的方式：使用 $set 或直接替换整个 calendarOptions 对象
        this.$set(this.calendarOptions, 'events', events);

        // 如果日历已经渲染，强制更新
        this.$nextTick(() => {
          if (this.$refs.fullCalendar) {
            this.$refs.fullCalendar.getApi().refetchEvents();
            // 确保日历重新渲染
            this.$refs.fullCalendar.getApi().updateSize();
          }
        });

        this.reserveVisibale = true;
        this.loading = false;
      }).catch(err => {
        console.error('获取预约列表失败:', err);
        this.$message.error('获取预约列表失败，请重试');
        this.loading = false;
      });
    },

    // 获取状态颜色
    getStatusColor(status) {
      const colors = { 0: '#f39c12', 1: '#28a745', 2: '#dc3545', 4: '#6c757d' };
      return colors[status] || '#378006';
    },

    // 点击事件回调
// 点击事件回调 - 获取用户详细信息
    handleEventClick(info) {
      const reservation = info.event.extendedProps;
      this.selectedReservation = { ...reservation };

      // 如果没有用户信息，则请求获取
      if (reservation.userId && !reservation.userInfo) {
        getUser(reservation.userId).then(response => {
          const user = response.data;

          // 构造用户信息对象
          const userInfo = {
            userName: user.userName || '未知',
            nickName: user.nickName || '无昵称',
            phonenumber: user.phonenumber || '无手机号',
            email: user.email || '无邮箱',
            sex: user.sex === '0' ? '男' : user.sex === '1' ? '女' : '未知',
            avatar: user.avatar || require('@/assets/images/profile.jpg'),
            company: user.company || '未知公司',
            deptName: user.deptName || '未知部门',
            roles: user.roles?.map(r => r.roleName) || []
          };

          // 合并用户信息到 selectedReservation
          this.selectedReservation = {
            ...reservation,
            userInfo
          };
        });
      } else if (reservation.userInfo) {
        // 如果已有用户信息直接展示
        this.selectedReservation = { ...reservation };
      }

      this.showReservationDetail = true;
    },


    // 修改预约状态
    changeReserveStatus(row, status) {
      if (!row) return;

      this.loading = true;

      changeStatus({ id: row.id, status }).then((response) => {
        this.$modal.msgSuccess("审核成功");

        // 1. 安全地更新当前选中的预约状态
        if (this.selectedReservation && this.selectedReservation.id === row.id) {
          // 创建新对象而不是直接修改
          this.selectedReservation = {
            ...this.selectedReservation,
            status: status
          };
        }

        // 2. 关闭弹窗
        this.showReservationDetail = false;

        // 3. 立即更新日历中的事件状态（如果可能）
        this.updateCalendarEventStatus(row.id, status);

        // 4. 强制刷新日历显示
        this.$nextTick(() => {
          this.forceRefreshCalendar();
        });

        // 5. 延迟重新加载预约数据，确保后端数据已更新
        setTimeout(() => {
          if (this.searchId) {
            this.checkReserveList(this.searchId);
          }
        }, 1500); // 延迟1.5秒

      }).catch(err => {
        console.error('审核失败:', err);
        this.$message.error('审核失败，请重试');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 更新日历中的事件状态
    updateCalendarEventStatus(eventId, newStatus) {
      if (this.$refs.fullCalendar) {
        const calendarApi = this.$refs.fullCalendar.getApi();
        const event = calendarApi.getEventById(eventId.toString());

        if (event) {
          // 更新事件的扩展属性
          event.setExtendedProp('status', newStatus);
          // 更新事件颜色
          event.setProp('color', this.getStatusColor(newStatus));
          // 强制重新渲染
          calendarApi.refetchEvents();
        } else {
          this.$modal.msgError('未找到该事件');
        }
      }
    },

    // 强制刷新日历显示
    forceRefreshCalendar() {
      if (this.$refs.fullCalendar) {
        const calendarApi = this.$refs.fullCalendar.getApi();
        calendarApi.refetchEvents();
        calendarApi.updateSize();
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomNumber: null,
        roomName: null,
        maxPeople: null,
        roomDescription: null,
        status: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会议室";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRooms(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会议室";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRooms(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRooms(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(`是否确认删除会议室管理编号为"${ids}"的数据项？`)
        .then(() => delRooms(ids))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    getReservationDuration(reservation) {
      if (!reservation || !reservation.startTime || !reservation.endTime) {
        return '时间信息不完整';
      }
      const start = dayjs(reservation.startTime);
      const end = dayjs(reservation.endTime);
      const duration = end.diff(start, 'hour', true);
      return duration >= 1 ? `${duration.toFixed(1)}小时` : `${Math.round(duration * 60)}分钟`;
    },

    formatReservationDate(reservation) {
      if (!reservation || !reservation.startTime) {
        return '时间信息不完整';
      }
      return dayjs(reservation.startTime).format('YYYY-MM-DD');
    },

    formatReservationStartTime(reservation) {
      if (!reservation || !reservation.startTime) {
        return '时间信息不完整';
      }
      return dayjs(reservation.startTime).format('YYYY-MM-DD HH:mm:ss');
    },

    formatReservationEndTime(reservation) {
      if (!reservation || !reservation.endTime) {
        return '时间信息不完整';
      }
      return dayjs(reservation.endTime).format('YYYY-MM-DD HH:mm:ss');
    },

    formatDateTime(date) {
      if (!date) {
        return '时间信息不完整';
      }
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    },

    // 获取时间状态
    getTimeStatus(reservation) {
      if (!reservation || !reservation.startTime || !reservation.endTime) {
        return { text: '时间未知', type: 'info' };
      }

      const now = new Date();
      const startTime = new Date(reservation.startTime);
      const endTime = new Date(reservation.endTime);

      if (now < startTime) {
        return { text: '未开始', type: 'warning' };
      } else if (now >= startTime && now <= endTime) {
        return { text: '进行中', type: 'success' };
      } else if (now > endTime) {
        return { text: '已结束', type: 'info' };
      } else {
        return { text: '时间未知', type: 'info' };
      }
    },

    async handleExpandChange(row, expandedRows) {
      // 只有在展开时才加载数据，关闭时不加载
      const isExpanded = expandedRows && expandedRows.includes(row);
      if (!isExpanded) {
        // 关闭时直接返回，不加载
        return;
      }
      this.$set(this.roomLoading, row.id, true);
      try {
        const res = await getRooms(row.id);
        let reservations = res.data.roomReservations || [];
        await Promise.all(reservations.map(async (reserve) => {
          if (reserve.userId) {
            if (this.userCache[reserve.userId]) {
              this.$set(reserve, 'userInfo', this.userCache[reserve.userId]);
            } else {
              try {
                const userRes = await getUser(reserve.userId);
                const info = {
                  userName: userRes.data.userName || '未知',
                  nickName: userRes.data.nickName || '无昵称',
                  phonenumber: userRes.data.phonenumber || '-',
                  email: userRes.data.email || '无邮箱',
                  sex: userRes.data.sex === '0' ? '男' : userRes.data.sex === '1' ? '女' : '未知'
                };
                this.$set(reserve, 'userInfo', info);
                this.$set(this.userCache, reserve.userId, info);
              } catch {
                const info = { userName: '未知', phonenumber: '-' };
                this.$set(reserve, 'userInfo', info);
                this.$set(this.userCache, reserve.userId, info);
              }
            }
          } else {
            const info = { userName: '未知', phonenumber: '-' };
            this.$set(reserve, 'userInfo', info);
          }
        }));
        // 修复：先清空再赋值，确保响应式刷新
        this.$set(row, 'roomReservations', []);
        this.$nextTick(() => {
          this.$set(row, 'roomReservations', reservations);
        });
      } catch (error) {
        this.$set(row, 'roomReservations', []);
        this.$message.error('获取预约数据失败');
      } finally {
        this.$set(this.roomLoading, row.id, false);
      }
    },

    // 新增：手动刷新房间预约数据
    async refreshRoomReservations(row) {
      this.$delete(row, 'roomReservations'); // 删除缓存，触发重新加载
      await this.handleExpandChange(row, [row]);
    },

    // 新增：行内审核功能
    changeReserveStatusInList(roomRow, reserveRow, status) {
      this.loading = true;
      changeStatus({ id: reserveRow.id, status }).then(() => {
        this.$modal.msgSuccess("审核成功");
        reserveRow.status = status;
      }).catch(() => {
        this.$message.error("审核失败，请重试");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
};
</script>

<style lang="scss" scoped>
/* 日历容器样式 */
.fc {
  max-width: 100%;
  height: 900px;
  margin: 0 auto;
}

/* 日历头部样式 */
.fc-header-toolbar {
  margin-bottom: 1em;
}

/* 日期单元格样式 */
.fc-daygrid-day-frame {
  min-height: 120px;
  padding: 4px;
  box-sizing: border-box;
}

/* 事件卡片样式 */
.fc-event {
  font-size: 12px;
  padding: 3px;
  margin: 1px;
  border-radius: 3px;
  border: none;
  color: #fff;
  min-height: 70px;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.fc-event-main {
  width: 100%;
  overflow: hidden;
  padding: 1px;
}

.fc-event-title {
  white-space: normal;
  word-wrap: break-word;
}

/* 事件内容样式优化 */
.fc-event-main div {
  margin-bottom: 1px;
  line-height: 1.1;
}

/* 当天高亮样式 */
.fc-day-today {
  background-color: #f0f7ff !important;
}

/* 隐藏不必要的元素 */
.fc .fc-daygrid-day.fc-day-past {
  display: none;
}

/* 空白占位格样式 */
.fc-daygrid-day-empty {
  display: block;
  min-height: 120px;
  pointer-events: none;
}

/* 调整月视图网格布局 */
.fc-daygrid-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

/* 确保表头对齐 */
.fc-col-header {
  width: 100% !important;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

/* 预约详情弹窗样式 */
.reservation-detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.reservation-detail-dialog .el-input {
  font-size: 13px;
}

.reservation-detail-dialog .el-tag {
  font-size: 12px;
}
</style>
